<?php
namespace mobile;
use mobile\libs\Helper;
use mobile\libs\Request;
use mobile\libs\CRedis;
use mobile\libs\Curl;
use mobile\parser as parser;

class Boot {
	protected $datas = array();
	
	protected $redis;
	
	public function __construct($datas) {
		$this->datas = $datas;
		$this->redis = CRedis::model();
	}
	
	// 运行
	public function run() {
		
		if( !$this->redis->exists('finish_'.MOBILE) ) {
			
			$this->redis->setex('finish_'.MOBILE, 86400, 1);
			
			foreach($this->datas as $key => $item) {
				if(empty($item)) continue;
				printf("Begin Request: %s \n", $item['desc']);
				
				// 查询结果是已注册则跳过
				$log = $this->redis->hget('mobile_'.MOBILE, $key);
				if($log && $log[0] == 1) {
					$log[1] != $item['desc'] && $this->redis->hset('mobile_'.MOBILE, $key, [$log[0], $item['desc']]);
					continue;
				}
				
				$res = Request::run($item);
				$this->logResult($item, $key, $res);
			}
		}

		Helper::clear();
	}
	
	/**
	 * 记录查询日志
	 */
	protected function logResult($item, $key, $res) {
		@ list($class, $method, $args) = $item['parser'];
		if($class == 'string') $class = 'str';
		$class = 'mobile\\parser\\'.ucfirst($class);
		
		$res = ( new $class($res) )->{$method}($args);
		
		echo $res[1], "\n";
		if($res[0]==1) {
			// 记录已注册的
			$this->redis->hset('mobile_'.MOBILE, $key, [$res[0], $item['desc'], time()]);
		} else if($res[0]==3) {
			// 判断为查询失败的
			$this->redis->hIncrBy('count_failed', $key, 1);
		}
	}
}

class AutoLoad {
	public static function load($className) {
		$className = str_replace('\\', '/', substr($className, 6));
		
		$filename = DIR.'/src/'.$className.'.php';
		
		if(is_file($filename)) {
			include($filename);
			return true;
		}
		
		return false;
	}
}

spl_autoload_register(array('mobile\AutoLoad','load'));
